package top.yudoge.dogeeditor.commons.utils

import com.google.gson.Gson
import top.yudoge.dogeeditor.commons.exceptions.ConvertException

inline fun <reified DST, reified SRC> SRC.convert(
    conv: (dst: DST, src: SRC) -> Unit = { _, _ -> /* ignore */ }
): DST {
    val dstClz = DST::class.java

    try {
        val gson = Gson()
        val json = gson.toJson(this)
        val bean = gson.fromJson(json, dstClz)

        conv(bean, this)

        return bean
    } catch (e: Exception) {
        throw ConvertException("error when execute convert", e)
    }
}

inline fun <reified DST, reified SRC> List<SRC>.convertList(
    conv: (dst: DST, src: SRC) -> Unit = { _, _ -> /* ignore */ }
): List<DST> {
    return this.map { it.convert(conv) }
}

inline fun Any.toJsonStr(): String {
    val gson = Gson()
    val json = gson.toJson(this)
    return json
}

inline fun <reified T> String.jsonToBean(): T {
    val gson = Gson()
    val bean = gson.fromJson(this, T::class.java)
    return bean
}